package com.ly.hotel.view.floatWindows;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.SysConf;
import com.ly.hotel.util.ImageUtil;
import com.ly.hotel.util.LanguageUtil;
import com.ly.hotel.util.QRImageUtil;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

public class QRFloatWin extends Service{
	// 定义浮动窗口布局
	private RelativeLayout mFloatLayout;
	private LayoutParams wmParams;
	// 创建浮动窗口设置布局参数的对象
	private WindowManager mWindowManager;
    private ImageView qrView = null;
    private ImageView jishiView = null;
    private TextView qrText = null;
    private Timer fx_timer = null;
    private Timer ad_timer = null;
    private Button noChatBtn = null;
    private final static int MSG_REFLASH = 0;
    private final static int MSG_SHOW_ME = 1;
    private final static int MSG_HIDE_ME = 2;
    private final static int MSG_SHOW_CHAT_REQUEST = 3;
    private final static int MSG_SHOW_CHAT_REQUEST_TIMEOUT = 4;
    private ThisHandler handlerMsg;
    private String qrStr = "";
    private String adUrl = "";
    private MyApplication app;
    private boolean isChatQrCodeShow = false;
    private boolean isAdQrCodeShow = false;
    private String adTips = "广告";					//广告二维码标题
    
    @Override  
    public IBinder onBind(Intent intent) {  
        return null;  
    }  
  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        wmParams = new LayoutParams();
		getApplication();
		
		app = (MyApplication) getApplication();
		
		handlerMsg = new ThisHandler(QRFloatWin.this);
		// 获取WindowManagerImpl.CompatModeWrapper
		mWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);

		DisplayMetrics dm = new DisplayMetrics();
		mWindowManager.getDefaultDisplay().getMetrics(dm);

		// 设置window type
		wmParams.type = LayoutParams.TYPE_PHONE;;
		// 设置图片格式，效果为背景透明
		wmParams.format = PixelFormat.RGBA_8888;
		// 设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
		wmParams.flags =
		// LayoutParams.FLAG_NOT_TOUCH_MODAL |
		LayoutParams.FLAG_NOT_FOCUSABLE |
		LayoutParams.FLAG_NOT_TOUCHABLE
		;

		// 调整悬浮窗显示的停靠位置为左侧置顶
		wmParams.gravity = Gravity.RIGHT | Gravity.BOTTOM;
		// 以屏幕左上角为原点，设置x、y初始值
		// 设置悬浮窗口长宽数据
		wmParams.width = LayoutParams.WRAP_CONTENT;
		wmParams.height = LayoutParams.WRAP_CONTENT;
		wmParams.x = getResources().getDimensionPixelOffset(R.dimen.px6);//20;
		wmParams.y =  getResources().getDimensionPixelOffset(R.dimen.px165);//111;
		LayoutInflater inflater = LayoutInflater.from(getApplication());
		// 获取浮动窗口视图所在布局
		mFloatLayout = (RelativeLayout) inflater.inflate(R.layout.qr_float_layout, null);
        qrView = (ImageView) mFloatLayout.findViewById(R.id.qr_float_id);
        jishiView = (ImageView) mFloatLayout.findViewById(R.id.jishi_pic);
        qrText = (TextView) mFloatLayout.findViewById(R.id.qr_tips);
        qrText.setText(getTips());
        noChatBtn  = (Button) mFloatLayout.findViewById(R.id.no_chat_push);
        Log.i("qr", "创建二维码浮窗");
        
		// 添加mFloatLayout
		mWindowManager.addView(mFloatLayout, wmParams);
		mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
				View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        qrView.setVisibility(View.VISIBLE);
        noChatBtn.setVisibility(View.INVISIBLE);
        initReflashTimer();
        initAdflashTimer();
        initListen();
    }  

    private void initListen() {
    	if(noChatBtn != null){
    		noChatBtn.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					MyApplication.chatQrCodeDisturb = true;
					if(handlerMsg.hasMessages(MSG_SHOW_CHAT_REQUEST_TIMEOUT)){
						handlerMsg.removeMessages(MSG_SHOW_CHAT_REQUEST_TIMEOUT);
					}
					handlerMsg.sendEmptyMessage(MSG_SHOW_CHAT_REQUEST_TIMEOUT);
					
					if(handlerMsg.hasMessages(MSG_HIDE_ME)){
						handlerMsg.removeMessages(MSG_HIDE_ME);
					}
					Log.i("qr", "客户点了别烦我，马上隐藏...");
					handlerMsg.sendEmptyMessage(MSG_HIDE_ME);
				}
			});
    	}
    }
    
    private String getTips(){
    	String tips = "";
    	tips = SysConf.extendConfGetValue(SysConf.SYS_CONF_QR_CODE_TIPS, "");
    	
    	if(tips.equals("")){
    		tips = this.getString(R.string.qr_code_tips);
    	} else {
    		tips = LanguageUtil.getTextFromLocalLanguage(tips);
    	}
    	return tips;
    }

    //获取二维码隐藏时间，0表示不隐藏
    private long getTimes(){
		long time = 15;
		String tm = SysConf.extendConfGetValue(SysConf.SYS_CONF_QR_TIME, "15");
		try {
			time = Long.parseLong(tm);
		} catch (NumberFormatException e) {
			Log.e("QRFloatWin", "配置qeTime含有非法字符！");
		}
		return time;
	}
    
    //定时器30秒初始化一次广告链接展示状态
    private void initAdflashTimer() {
    	
	    	ad_timer = new Timer(true);
	
			TimerTask task = new TimerTask() {
				@Override
				public void run() {
					String adConf = SysConf.extendConfGetValue(SysConf.SYS_CONF_AD_QR_URL, "");
					
					if(!TextUtils.isEmpty(adConf)){
						String info[] = adConf.split(";");
						//有广告链接
						adUrl = info[0];
						if(!TextUtils.isEmpty(info[1])){
							adTips = info[1];
						}
						if(!isAdQrCodeShow || !SysConf.extendConfGetValue(SysConf.SYS_CONF_SHOW_QR, "1").equals("1") || TextUtils.isEmpty(MyApplication.clouldCtlUrl)) {
							isAdQrCodeShow = true;
						}else {
							isAdQrCodeShow = false;
						}
					}
				}
			};
			
			ad_timer.schedule(task, 100, 30000);	//每30秒检测一次
	}
    
	private void initReflashTimer() {
		fx_timer = new Timer(true);

		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				handlerMsg.sendEmptyMessage(MSG_REFLASH);
				
				String name = app.getTopActivity();
				if(MyApplication.chatQrCodeInfo != null){
					//有技师发来的聊天邀请
					if(!isChatQrCodeShow){
						handlerMsg.sendEmptyMessage(MSG_SHOW_ME);
						handlerMsg.sendEmptyMessage(MSG_SHOW_CHAT_REQUEST);
						handlerMsg.sendEmptyMessageDelayed(MSG_SHOW_CHAT_REQUEST_TIMEOUT, 120 * 1000);
						if(handlerMsg.hasMessages(MSG_HIDE_ME)){
							handlerMsg.removeMessages(MSG_HIDE_ME);
						}
						Log.i("qr", "2分钟后隐藏...");
						handlerMsg.sendEmptyMessageDelayed(MSG_HIDE_ME, 120 *1000);
					}
				} else {
					if((MyApplication.clouldCtlUrl.equals("") || !SysConf.extendConfGetValue(SysConf.SYS_CONF_SHOW_QR, "1").equals("1"))
							&& !isAdQrCodeShow ){
						//没有获取到sickid，就隐藏之
						handlerMsg.sendEmptyMessage(MSG_HIDE_ME);
					} else {
						if(name.contains("TabHostActivity")){
							//在主activity，就显示之
							handlerMsg.sendEmptyMessage(MSG_SHOW_ME);
							if(handlerMsg.hasMessages(MSG_HIDE_ME)){
								handlerMsg.removeMessages(MSG_HIDE_ME);
							}
						}else{
							//等待15秒后隐藏
							if(getTimes() != 0) {
								if (!handlerMsg.hasMessages(MSG_HIDE_ME)) {
									Log.i("qr", "15秒后隐藏...");
									handlerMsg.sendEmptyMessageDelayed(MSG_HIDE_ME, 15 * 1000);
								}
							}
						}
					}
				}
			}
		};
		
		fx_timer.schedule(task, 100, 4000);
	}

    @Override  
    public void onStart(Intent intent, int startId) {  
        super.onStart(intent, startId);  
    }  

    @Override  
    public void onDestroy() {  
        super.onDestroy();  
    }  
    
    private static class ThisHandler extends Handler {
		private WeakReference<QRFloatWin> wrActivity;

		public ThisHandler(QRFloatWin activity) {
			wrActivity = new WeakReference<QRFloatWin>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			QRFloatWin act = wrActivity.get();
			if (act != null) {
				// 这个是通过事实消息接口获取的弹窗信息打开的
				if(message.what == MSG_REFLASH){
					if(act.isAdQrCodeShow){
						act.qrView.setBackgroundDrawable(new BitmapDrawable(new QRImageUtil().createQRCode(act.adUrl)));
						act.qrText.setText(act.adTips);
					}else{
						if(!MyApplication.clouldCtlUrl.equals("")  &&
						SysConf.extendConfGetValue(SysConf.SYS_CONF_SHOW_QR, "1").equals("1")){
							if(act.qrStr.equals("") || !act.qrStr.equals(MyApplication.clouldCtlUrl) || !act.isAdQrCodeShow){
								act.qrStr = MyApplication.clouldCtlUrl;
								act.qrView.setBackgroundDrawable(new BitmapDrawable(new QRImageUtil().createQRCode(act.qrStr)));
								act.qrText.setText(act.getTips());
							}
						} 
					}
				}else if(message.what == MSG_SHOW_ME){
					if(!act.qrStr.equals("") || act.isAdQrCodeShow){
//						Log.v("qr", "显示二维码浮窗," + act.qrStr);
						act.qrView.setVisibility(View.VISIBLE);
						act.qrText.setVisibility(View.VISIBLE);
						act.jishiView.setVisibility(View.INVISIBLE);
						act.noChatBtn.setVisibility(View.INVISIBLE);
					}
				}else if(message.what == MSG_HIDE_ME){
					Log.v("qr", "隐藏二维码浮窗," + act.qrStr);
					act.qrView.setVisibility(View.INVISIBLE);
					act.qrText.setVisibility(View.INVISIBLE);
					act.jishiView.setVisibility(View.INVISIBLE);
					act.noChatBtn.setVisibility(View.INVISIBLE);
				}else if(message.what == MSG_SHOW_CHAT_REQUEST){
					Log.v("qr", "显示技师聊天邀请二维码," + MyApplication.chatQrCodeInfo.url);
					act.isChatQrCodeShow = true;
					act.qrView.setBackgroundDrawable(new BitmapDrawable(new QRImageUtil().createQRCode(MyApplication.chatQrCodeInfo.url)));
					act.qrText.setText(MyApplication.chatQrCodeInfo.tips);
					ImageUtil.displayImage(act, MyApplication.getHostResUrl() 
							+ "upload/interface/technician/pic/" + MyApplication.chatQrCodeInfo.num + ".jpg" , act.jishiView);
					Animation shake = AnimationUtils.loadAnimation(act, R.anim.shake);//加载动画资源文件
					act.jishiView.setVisibility(View.VISIBLE);
					if(!MyApplication.chatQrCodeDisturb){
						act.noChatBtn.setVisibility(View.VISIBLE);
					}
					act.qrView.startAnimation(shake); //给组件播放动画效果
				}else if(message.what == MSG_SHOW_CHAT_REQUEST_TIMEOUT){
					Log.v("qr", "技师聊天邀请二维码超时," + act.qrStr);
					MyApplication.chatQrCodeInfo = null;
					act.isChatQrCodeShow = false;
					act.qrStr = "";
					sendEmptyMessage(MSG_REFLASH);
				}
			}
		}
	}
}
